package Controller.DepServlet;

import Dao.DepDao;
import bean.Dep;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/dep_add")
public class dep_add extends HttpServlet {
    DepDao depDao = new DepDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String dno = req.getParameter("dno");
        String dname = req.getParameter("dname");
        String tel = req.getParameter("tel");
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        Dep d1 = depDao.selectByDno(dno);
        Dep d2 = depDao.selectByDname(dname);
        if (d1 == null && d2 == null) {
            depDao.insert(dno, dname, tel);
            map.put("msg", "添加成功!");
            System.out.println("添加成功!");
        } else if (d1 != null) {
            map.put("code", 400);
            map.put("msg", "添加失败，该系部编号已存在!");
            System.out.println("添加失败，该系部编号已存在!");
        } else if (d2 != null) {
            map.put("code", 401);
            map.put("msg", "添加失败，该系部名称已存在!");
            System.out.println("添加失败，该系部名称已存在!");
        }
        resp.getWriter().write(JSON.toJSONString(map));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
